//
//  UIViewController+Extension.m
//  AmountBody
//
//  Created by Qiu Jishuai on 2018/1/2.
//  Copyright © 2018年 RCMTM. All rights reserved.
//

#import "NSObject+Extension.h"

@implementation NSObject (Extension)

+ (UIViewController *)topViewController {

    UIViewController *root;
    NSArray *windows = UIApplication.sharedApplication.windows;
    for (UIWindow *window in windows) {
        UIViewController *windowRoot = window.rootViewController;
        if (windowRoot) {
            root = windowRoot;
            break;
        }
    }

    return [self topMostOfViewController: root];
}

+ (UIViewController *)topMostOfViewController: (UIViewController *)viewController {

 // presented view controller
    UIViewController *presentedViewController = viewController.presentedViewController;
    if (presentedViewController) {
        return [self topMostOfViewController:presentedViewController];
    }

    // UITabBarController
    if ([viewController isKindOfClass:[UITabBarController class]]) {
        MainTabBarController *tabbarController = (MainTabBarController *)viewController;
        UIViewController *selectedViewController = tabbarController.selectedViewController;
        if (selectedViewController) {
            return [self topMostOfViewController: selectedViewController];
        }
    }

    // UINavigationController
    if ([viewController isKindOfClass:[UINavigationController class]]) {
        UINavigationController *navigationController = (UINavigationController *)viewController;
        UIViewController *visibleViewController = navigationController.visibleViewController;
        if (visibleViewController) {
            return [self topMostOfViewController: visibleViewController];
        }
    }

    // UIPageController
    if ([viewController isKindOfClass:[UIPageViewController class]]) {
        UIPageViewController *pageViewController = (UIPageViewController *)viewController;
        if (pageViewController.viewControllers.count == 1) {
            return [self topMostOfViewController: pageViewController.viewControllers.firstObject];
        }
    }

    // child view controller
    if (viewController.view.subviews) {
        for (UIView *subview in viewController.view.subviews) {
            UIResponder *responder = (UIResponder *)subview.nextResponder;
            if ([responder isKindOfClass:[UIViewController class]]) {
                return [self topMostOfViewController: (UIViewController *)responder];
            }
        }
    }

    return viewController;
}


@end
